import json
import logging
import threading
import tkinter as tk
from src.signer import Signer
from tkinter import ttk, scrolledtext, messagebox


class ManualTab:
    def __init__(self, base):
        self.base = base
        self.signer = Signer()

    def setup_manual_tab(self, parent):
        """设置数据加签界面"""
        # 数据输入区域
        data_frame = ttk.LabelFrame(parent, text="业务数据", padding=10)
        data_frame.pack(fill='x', padx=5, pady=5)

        self.data_text = scrolledtext.ScrolledText(data_frame, height=10, width=70)
        self.data_text.pack(fill='both', expand=True)

        # 默认数据示例
        default_data = ('"sessionID":"{sessionID}"||'
                        + '"payExchangeInfoHead":"{payExchangeInfoHead}"||'
                        + '"payExchangeInfoLists":"{payExchangeInfoLists}"||'
                        + '"serviceTime":"{time_str}"')
        self.data_text.insert('1.0', default_data)

        # 按钮区域
        button_frame = ttk.Frame(parent)
        button_frame.pack(fill='x', padx=5, pady=5)

        ttk.Button(button_frame, text="加签",
                   command=self.execute_manual_task).pack(side='left', padx=5)
        # ttk.Button(button_frame, text="加签并发送",
        #            command=self.execute_manual_task).pack(side='left', padx=5)
        ttk.Button(button_frame, text="清空数据",
                   command=self.clear_data).pack(side='left', padx=5)

        # 结果显示区域
        result_frame = ttk.LabelFrame(parent, text="执行结果", padding=10)
        result_frame.pack(fill='both', expand=True, padx=5, pady=5)

        self.result_text = scrolledtext.ScrolledText(result_frame, height=8)
        self.result_text.pack(fill='both', expand=True)


    def execute_manual_task(self):
        """执行手动任务"""
        def run_task():
            try:
                # 获取输入数据
                data_str = self.data_text.get('1.0', tk.END).strip()
                # business_data = json.loads(data_str)

                # 执行加签和发送
                result = self.signer.sign(data_str)

                # 显示结果
                self.result_text.delete('1.0', tk.END)
                self.result_text.insert('1.0', result)

            except Exception as e:
                messagebox.showerror("错误", f"执行失败: {str(e)}")
                logging.error(f"手动任务执行失败: {e}")

        # 在新线程中执行任务，避免界面卡顿
        threading.Thread(target=run_task, daemon=True).start()

    def clear_data(self):
        """清空数据"""
        self.data_text.delete('1.0', tk.END)


    def sign_and_send_task(self):
        """执行手动任务"""
        def run_task():
            try:
                # 获取输入数据
                data_str = self.data_text.get('1.0', tk.END).strip()
                business_data = data_str

                # 执行加签和发送
                result = self.signer.sign_and_send(business_data)

                # 显示结果
                self.result_text.delete('1.0', tk.END)
                self.result_text.insert('1.0', json.dumps(result, indent=2, ensure_ascii=False))

            except Exception as e:
                messagebox.showerror("错误", f"执行失败: {str(e)}")
                logging.error(f"手动任务执行失败: {e}")

        # 在新线程中执行任务，避免界面卡顿
        threading.Thread(target=run_task, daemon=True).start()